package com.gzu.finalwork.courier.controller;

import com.gzu.finalwork.courier.service.CourierService;
import com.gzu.finalwork.common.utils.AjaxResult;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 配送员控制器
 */
@RestController
@RequestMapping("/courier")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class CourierController {

    @Autowired
    private CourierService courierService;

    /**
     * 获取可接订单列表（状态为0-待揽收）
     * @param pageNum 页码，默认1
     * @param pageSize 每页大小，默认10
     * @return 可接订单列表
     */
    @GetMapping("/available-orders")
    public Object getAvailableOrders(@RequestParam(defaultValue = "1") int pageNum,
                                   @RequestParam(defaultValue = "10") int pageSize) {
        try {
            return courierService.getAvailableOrders(pageNum, pageSize);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取可接订单失败：" + e.getMessage());
        }
    }

    /**
     * 配送员接单
     * @param orderId 订单ID
     * @param remark 接单备注（可选）
     * @param session HTTP会话
     * @return 接单结果
     */
    @PostMapping("/accept-order")
    public Object acceptOrder(@RequestParam Long orderId,
                            @RequestParam(required = false) String remark,
                            HttpSession session) {
        try {
            // 从session获取当前登录用户ID
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return AjaxResult.error(401, "用户未登录");
            }
            
            // 根据userId查询对应的配送员ID
            Long courierId = courierService.getCourierIdByUserId(userId);
            if (courierId == null) {
                return AjaxResult.error(403, "当前用户不是配送员");
            }
            
            return courierService.acceptOrder(orderId, courierId, remark);
        } catch (Exception e) {
            return AjaxResult.error(500, "接单失败：" + e.getMessage());
        }
    }

    /**
     * 获取配送员的配送记录
     * @param pageNum 页码，默认1
     * @param pageSize 每页大小，默认10
     * @param session HTTP会话
     * @return 配送记录列表
     */
    @GetMapping("/my-assignments")
    public Object getMyCourierAssignments(@RequestParam(defaultValue = "1") int pageNum,
                                        @RequestParam(defaultValue = "10") int pageSize,
                                        HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return AjaxResult.error(401, "用户未登录");
            }
            
            // 根据userId查询对应的配送员ID
            Long courierId = courierService.getCourierIdByUserId(userId);
            if (courierId == null) {
                return AjaxResult.error(403, "当前用户不是配送员");
            }
            
            return courierService.getCourierAssignments(courierId, pageNum, pageSize);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取配送记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单详情
     * @param orderId 订单ID
     * @return 订单详情
     */
    @GetMapping("/order-details/{orderId}")
    public Object getOrderDetails(@PathVariable Long orderId) {
        try {
            return courierService.getOrderDetails(orderId);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取订单详情失败：" + e.getMessage());
        }
    }

    /**
     * 根据订单ID获取物流轨迹
     * @param orderId 订单ID
     * @param session HTTP会话
     * @return 物流轨迹信息
     */
    @GetMapping("/track/{orderId}")
    public Object getDeliveryTrack(@PathVariable Long orderId, HttpSession session) {
        try {
            return courierService.getDeliveryTrack(orderId, session);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取物流轨迹失败：" + e.getMessage());
        }
    }

    /**
     * 添加物流轨迹
     * @param orderId 订单ID
     * @param location 位置信息
     * @param remark 备注（可选）
     * @param session HTTP会话
     * @return 添加结果
     */
    @PostMapping("/track/{orderId}")
    public Object addDeliveryTrack(@PathVariable Long orderId,
                                 @RequestParam String location,
                                 @RequestParam(required = false) String remark,
                                 HttpSession session) {
        try {
            return courierService.addDeliveryTrack(orderId, location, remark, session);
        } catch (Exception e) {
            return AjaxResult.error(500, "添加物流轨迹失败：" + e.getMessage());
        }
    }

    /**
     * 获取配送员仪表盘数据
     * @param session HTTP会话
     * @return 仪表盘统计数据
     */
    @GetMapping("/dashboard")
    public Object getDashboard(HttpSession session) {
        try {
            // 从session获取当前登录用户ID
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return AjaxResult.error(401, "用户未登录");
            }
            
            // 根据userId查询对应的配送员ID
            Long courierId = courierService.getCourierIdByUserId(userId);
            if (courierId == null) {
                return AjaxResult.error(403, "当前用户不是配送员");
            }
            
            return courierService.getDashboardData(courierId);
        } catch (Exception e) {
            return AjaxResult.error(500, "获取仪表盘数据失败：" + e.getMessage());
        }
    }
} 